package org.jeecg.modules.wlhy.customer.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.constant.UserTypeEnum;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.wlhy.customer.entity.HyCustomer;
import org.jeecg.modules.wlhy.customer.entity.HyCustomerUser;
import org.jeecg.modules.wlhy.customer.service.IHyCustomerUserService;
import org.jeecg.modules.wlhy.customer.vo.SysUserCustomerUser;
import org.jeecg.modules.wlhy.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @Description: 货主子账号
* @Author: duanlikao
* @Date:   2020-11-30
* @Version: V1.0
*/
@Api(tags="货主管理-子账号信息")
@RestController
@RequestMapping("/customer/hyCustomerUser/")
@Slf4j
public class HyCustomerUserController extends JeecgController<HyCustomerUser, IHyCustomerUserService> {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IHyCustomerUserService hyCustomerUserService;

    @Value(value="${customer.role_sub_jdy:}")
    private String customerJdyRoleID;

    @Value(value="${customer.role_sub_caiwu:}")
    private String customerCaiwuRoleID;

    @Value(value="${customer.role_sub_yuliu:}")
    private String customerYuliuRoleID;

    @Value(value="${customer.role_sub_yuliu2:}")
    private String customerYuliu2RoleID;

    @Autowired
    private UserUtil userUtil;

    /**
     * 获取货主子账号用户列表数据
     * @param user
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */

//    @AutoLog(value = "货主管理-子账号信息-分页列表查询")
    @ApiOperation(value="货主管理-子账号信息-分页列表查询", notes="货主管理-子账号信息-分页列表查询")
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public Result<?> queryPageList(SysUserCustomerUser user, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   HttpServletRequest req) {
        HyCustomer customer = userUtil.getCustomer();
        if (customer == null) {
           return Result.error("货主信息错误");
        }
        String customerId = customer.getId();
        Page<SysUserCustomerUser> userPage = new Page<SysUserCustomerUser>(pageNo, pageSize);
        IPage<SysUserCustomerUser> userpageList = hyCustomerUserService.getUserListByCustomerId(userPage , customerId);
        return Result.OK(userpageList);
    }

    /**
     * 添加
     * @param jsonObject
     * @return
     */
    @AutoLog(value = "货主子账号-添加")
    @ApiOperation(value="货主子账号-添加", notes="货主子账号-添加")
    @RequestMapping(value = "add", method = RequestMethod.POST)
    @Transactional
    @RequiresPermissions("customer:user:add")
    public Result<?> add(@RequestBody JSONObject jsonObject) {

       String phone =  jsonObject.getString("phone") ;

        String selectedRole = jsonObject.getString("roleId");
        if(!customerJdyRoleID.equals(selectedRole)
        && !customerCaiwuRoleID.equals(selectedRole)
        && !customerYuliuRoleID.equals(selectedRole)
        && !customerYuliu2RoleID.equals(selectedRole)) {
            return Result.error("角色选择错误");
        }

        if(StringUtils.isEmpty(selectedRole)){
            return Result.error("角色不能为空");
        }

        HyCustomer customer = userUtil.getCustomer();
        if (customer == null) {
            return Result.error("货主信息错误");
        }

        SysUser sysUser2 = sysUserService.getUserByPhone(phone);
        if (sysUser2 != null) {
            return Result.error("该手机号已注册");
        }

        String customerId = customer.getId();

        SysUser user = jsonObject.toJavaObject(SysUser.class);
        //String username = phone;//设置登陆账号为手机号
        String username = sysUserService.createRandomUserName();//随机生成账号
        user.setUsername(username);
        user.setPhone(phone);
        user.setUType(UserTypeEnum.货主子账号.getCode());//货主子账号
        user.setCreateTime(new Date());
        String salt = oConvertUtils.randomGen(8);
        user.setSalt(salt);
        String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
        user.setPassword(passwordEncode);
        user.setStatus(1);
        user.setDelFlag(CommonConstant.DEL_FLAG_0);
        sysUserService.addUserWithRole(user, selectedRole);//角色
        sysUserService.addUserWithDepart(user, customer.getOrgId());//部门

        HyCustomerUser hyCustomerUser = new HyCustomerUser();
        hyCustomerUser.setRoleId(selectedRole);
        hyCustomerUser.setUserId(user.getId());
        hyCustomerUser.setCustomerId(customerId);
        hyCustomerUser.setDelFlag("0");
        hyCustomerUser.setIzUsed("1");
        hyCustomerUserService.save(hyCustomerUser);

        return Result.OK("添加成功！");
    }

    /**
     *  编辑
     *
     * @param jsonObject
     * @return
     */
    @AutoLog(value = "货主子账号-编辑")
    @ApiOperation(value="货主子账号-编辑", notes="货主子账号-编辑")
    @PutMapping(value = "edit")
    @RequiresPermissions("customer:user:edit")
    public Result<?> edit(@RequestBody JSONObject jsonObject) {
        HyCustomer customer = userUtil.getCustomer();
        if (customer == null) {
            return Result.error("货主信息错误");
        }
        String phone =  jsonObject.getString("phone") ;
        SysUser user = jsonObject.toJavaObject(SysUser.class);
        String id = user.getId();
        //检查手机号是否已存在
        List<SysUser> list = sysUserService.list(new QueryWrapper<SysUser>()
                .eq("phone", phone)
                .ne("id", id));
        if(list.size() >0){
            return Result.error("手机号已被占用");
        }

//        user.setUsername(phone);
        user.setPhone(phone);
        sysUserService.updateById(user);
        return Result.OK("修改成功!");
    }


    /**
     *   通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "货主子账号-通过id删除")
    @ApiOperation(value="货主子账号-通过id删除", notes="货主子账号-通过id删除")
    @DeleteMapping(value = "delete")
    @Transactional
    @RequiresPermissions("customer:user:delete")
    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
        HyCustomer customer = userUtil.getCustomer();
        if (customer == null) {
            return Result.error("货主信息错误");
        }
        HyCustomerUser hyCustomerUser = hyCustomerUserService.getInfoByUserId(id);
        hyCustomerUserService.removeById(hyCustomerUser.getId());
        this.sysUserService.deleteUser(hyCustomerUser.getUserId());
        return Result.OK("删除成功!");
    }

}
